package com.ls.demo.http.server;

import com.ls.demo.http.config.HttpServerChannelInitializer;
import com.ls.demo.http.config.HttpServerProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * @author liShan
 * @date 2019/8/31 14:52
 */
@Component
public class HttpServer implements Runnable {

    @Resource
    private ServerBootstrap httpServerBootstrap;

    @Resource
    private HttpServerChannelInitializer serverChannelInitializer;

    @Resource
    private EventLoopGroup httpBossEventLoopGroup;

    @Resource
    private EventLoopGroup httpWorkEventLoopGroup;

    @Resource
    private HttpServerProperties httpServerProperties;

    private ChannelFuture start() {
        httpServerBootstrap.group(httpBossEventLoopGroup, httpWorkEventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(serverChannelInitializer);
        ChannelFuture future = null;
        try {
            future = httpServerBootstrap.bind(new InetSocketAddress(httpServerProperties.getPort())).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return future;
    }

    @Override
    public void run() {
        ChannelFuture channelFuture = this.start();
        if (null != channelFuture){
            try {
                channelFuture.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
